package page;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

/**
 * Servlet implementation class SupprimerSouhaitServlet
 */
public class SupprimerSouhaitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SupprimerSouhaitServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		RequestDispatcher dis;
		Connection con = null;
		
		Integer membre = (Integer)session.getAttribute("user_id");
		if(membre == null){
			dis = request.getRequestDispatcher("/login.jsp");
			dis.forward(request, response);
			return;
		}
		
		String souhait = request.getParameter("souhait");
		Integer idSouhait = 0;
		try{
			idSouhait = Integer.parseInt(souhait);
		}catch(NumberFormatException e){
			e.printStackTrace();
		}
		
		try{
			Context namingContext;
			PreparedStatement pstmt;
			
			namingContext = new InitialContext();
			DataSource dataSource = (DataSource)namingContext.lookup("java:comp/env/jdbc/MiniIBay");
			con = dataSource.getConnection();
			
			pstmt = con.prepareStatement("DELETE FROM `souhait` WHERE id_produit=? AND id_membre=?");
			pstmt.setInt(1, idSouhait);
			pstmt.setInt(2, membre);
			
			pstmt.executeUpdate();
			
			dis = request.getRequestDispatcher("messouhaits");
			dis.forward(request, response);
		}catch(NamingException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("messouhaits");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("messouhaits");
		} finally {
			try {
				if(con != null) con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
